package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.TreeNode;

/**
 * 从前序与中序遍历序列构造二叉树
 * https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 *
 * @time 2024/1/9
 */
public class BuildTree {

//    public static void main(String[] args) {
//        BuildTree bt = new BuildTree();
//        int[] pre = {3, 9, 20, 15, 7};
//        int[] in = {9, 3, 15, 20, 7};
//        bt.buildTree(pre, in);
//    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode root = search(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
        return root;
    }

    private TreeNode search(int[] pre, int[] in, int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) {
            return null;
        }
        TreeNode root = new TreeNode(pre[preLeft]);
        if (preLeft == preRight) {
            return root;
        }

        for (int i = inLeft; i <= inRight; i++) {
            if (in[i] == pre[preLeft]) {
                if (i - inLeft > 0) {
                    root.left = search(pre, in, preLeft + 1, preLeft + i - inLeft, inLeft, i - 1);
                }

                int tmp = inRight - i;
                if (tmp > 0) {
                    root.right = search(pre, in, preLeft + 1 + i - inLeft, preRight, i + 1, inRight);
                }
                break;
            }
        }
        return root;
    }
}
